/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.ms1_intensitiesretrieval;

import java.io.File;
import java.util.List;
import org.apache.log4j.Logger;
import uk.ac.ebi.jmzml.model.mzml.CVParam;
import uk.ac.ebi.jmzml.model.mzml.Scan;
import uk.ac.ebi.jmzml.model.mzml.Spectrum;
import uk.ac.ebi.jmzml.xml.io.MzMLObjectIterator;
import uk.ac.ebi.jmzml.xml.io.MzMLUnmarshaller;

/**
 *
 * @author Jonas
 */
public class MzmlIterator {

    private static final Logger LOGGER = Logger.getLogger(MzmlIterator.class);
    CompareWithMSLims compareWithMSLims = new CompareWithMSLims();

    public void iterateAllSpectra(List<MSLimsHits> identifications, File mzmlFile) {

        // Unmarshall the provided mzmlFile once
        MzMLUnmarshaller unmarshaller = new MzMLUnmarshaller(mzmlFile);
        // Index all the spectra in the mzmlFile in a List
        MzMLObjectIterator<Spectrum> spectrumIterator = unmarshaller.unmarshalCollectionFromXpath("/run/spectrumList/spectrum", Spectrum.class);

        LOGGER.info("Scanning through mzML-file...");

        // Loop over all the spectra contained in the list
        while (spectrumIterator.hasNext()) {

            // Initiate spectrum with the next spectrum in the list
            Spectrum spectrum = spectrumIterator.next();
            // List al the CVParams of that spectrum, one of them includes info on the MS_level (1 or 2)
            List<CVParam> spectrumCVParams = spectrum.getCvParam();

            for (int i = 0; i < spectrumCVParams.size(); i++) {
                // Check if the spectrum is an MS1 spectrum
                if (spectrumCVParams.get(i).getAccession().equalsIgnoreCase("MS:1000511") && spectrumCVParams.get(i).getValue().equalsIgnoreCase("1")) {
                    // Get the retention time of the spectrum
                    // Make an ArrayList to hold this spectrums Scan node
                    List<Scan> spectrumScans = spectrum.getScanList().getScan();
                    List<CVParam> scanCVParams = spectrumScans.get(0).getCvParam();
                    // Set retentiontime at which the scan was made
                    double spectrumRetentionTime = Double.parseDouble((scanCVParams.get(0).getValue()));  
                    
                    // Give the spectrum to CompareWithMSLims where it shall be checked against the identificationsList
                    compareWithMSLims.checkWithMSLims(spectrumRetentionTime, spectrum, identifications);
                    break;
                }
            }
        }
        LOGGER.info("Scanning mzML-file: finished!");

    }
}
